package com.ruoyi.wxdaiqu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.wxdaiqu.feign.WxLoginFeignService;
import com.ruoyi.wxdaiqu.mapper.AnlysisMapper;
import com.ruoyi.wxdaiqu.mapper.HelplistMapper;
import com.ruoyi.wxdaiqu.pojo.Anlysis;
import com.ruoyi.wxdaiqu.pojo.Helplist;
import com.ruoyi.wxlogin.pojo.WxUser;
import com.ruoyi.wxcommon.common.Result;
import com.ruoyi.wxdaiqu.service.IHelplistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 帮助列表 服务实现类
 * </p>
 *
 * @author 凡哥哥
 * @since 2024-05-28
 */
@Service
public class HelplistServiceImpl extends ServiceImpl<HelplistMapper, Helplist> implements IHelplistService {

    @Autowired
    WxLoginFeignService wxLoginFeignService;
    @Autowired
    AnlysisMapper anlysisMapper;
    @Transactional
    @Override
    public Result addSubstitutionTask(Helplist helplist) {
        try {
            if ("失物认领".equals(helplist.getTitle()) && helplist.getPrice() == 0){
                helplist.setState(1);
                this.baseMapper.insert(helplist);
                return Result.SUCCESS("发布成功");
            }else {
                this.baseMapper.insert(helplist);
                return Result.SUCCESS("发布成功");
            }
        } catch (Exception e) {
            // TODO 记录日志
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result getAreaId(String get, Integer pageIndex, Integer pageSize, Integer aId,Integer wxId,Integer id) {
        if ("get".equals(get)){
            Page<Helplist> page = new Page<>(pageIndex,pageSize);
            QueryWrapper<Helplist> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete",1);
            queryWrapper.eq("a_id",aId);
            queryWrapper.eq("state",1);
            queryWrapper.orderByDesc("create_time");
            return getResult(page, queryWrapper);
        }
        if ("get2".equals(get)){
            Page<Helplist> page = new Page<>(pageIndex,pageSize);
            QueryWrapper<Helplist> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete",1);
            queryWrapper.eq("wx_id",wxId);
            queryWrapper.orderByDesc("create_time");
            return getResult(page, queryWrapper);
        }
        if ("get3".equals(get)){
            Page<Helplist> page = new Page<>(1,999);
            QueryWrapper<Helplist> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete",1);
            if (id != null){
                queryWrapper.eq("id",id);
            }else {
                queryWrapper.eq("jd_id",wxId);
            }

            queryWrapper.orderByDesc("jd_time");
            return getResult(page, queryWrapper);
        }


        Page<Helplist> page = new Page<>(pageIndex,pageSize);
        QueryWrapper<Helplist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",1);
        queryWrapper.eq("jd_id",wxId);
        return getResult(page, queryWrapper);


    }
    @Transactional
    @Override
    public Result jd(Integer id, String openId, String title, Integer jdId,Integer state) {
        Helplist helplist = this.baseMapper.selectById(id);
        if (helplist != null && helplist.getJdId() == null){
            helplist.setJdId(jdId);
            helplist.setJdTime(LocalDateTime.now());
            helplist.setState(state);
            this.baseMapper.updateById(helplist);
            return Result.SUCCESS("接单成功");
        }

        return Result.FAIL("接单失败");
    }

    /**
     * 付款功能
     * @param title
     * @param openId
     * @param price
     * @return
     */
    @Transactional
    @Override
    public Result pay(String title, String openId, Double price) {
//        WxUser wxUser = wxLoginFeignService.getByOpenId(openId);
//        Double payment = wxUser.getPayment();
//        double result = payment - price;
//        wxUser.setPayment(result);
        return null;
    }

    @Override
    public Result anlysisWxSm(Integer wxId, String yearMonth) {
        // 以 "-" 分割字符串
        String[] parts = yearMonth.split("-");
        String year = parts[0];
        String month = parts[1];
        Anlysis anlysis = anlysisMapper.byCreateTime(wxId,year,month);
        if (anlysis != null){
            return Result.SUCCESS(anlysis);
        }else {
            return Result.SUCCESS();
        }
    }
    @Transactional
    @Override
    public Result confirm(Integer id) {

        Helplist helplist = this.baseMapper.selectById(id);
        if (helplist != null){
            helplist.setState(3);
            helplist.setFinishTime(LocalDateTime.now());
            this.updateById(helplist);
            Integer wxId = helplist.getJdId();
            Anlysis result = anlysisMapper.byWxId(wxId);
            if (result == null){
                Anlysis anlysis = new Anlysis();
                anlysis.setWxId(wxId);
                anlysis.setGetFeeMonth(helplist.getPrice());
                anlysis.setCompleteTotalByMonth(1);
                anlysis.setCreateTime(LocalDateTime.now());
                anlysisMapper.insert(anlysis);
                return Result.SUCCESS("第一次帮助成功");
            }else {
                Double oldFeeMonth = result.getGetFeeMonth();
                Double newFeeMonth = oldFeeMonth + helplist.getPrice();
                Integer oldCompleteTotalByMonth = result.getCompleteTotalByMonth();
                Integer newCompleteTotalByMonth = oldCompleteTotalByMonth + 1;
                result.setGetFeeMonth(newFeeMonth);
                result.setCompleteTotalByMonth(newCompleteTotalByMonth);
                anlysisMapper.updateById(result);
                return Result.SUCCESS("帮助成功");
            }

        }

        return Result.FAIL();
    }

    private Result getResult(Page<Helplist> page, QueryWrapper<Helplist> queryWrapper) {
        Page<Helplist> page1 = this.page(page, queryWrapper);
        List<Helplist> result = page1.getRecords().stream().map(helplist -> {
            WxUser wxUser = wxLoginFeignService.getById(helplist.getWxId());
            helplist.setNickName(wxUser.getNickName());
            helplist.setAvatarUrl(wxUser.getAvatarUrl());
            helplist.setPhone(wxUser.getPhone());
            helplist.setDphone(wxUser.getDphone());
            return helplist;
        }).collect(Collectors.toList());
        page1.setRecords(result);
        return Result.SUCCESS(page1);
    }

    @Override
    public Result updateState(Integer oId, Integer state) {
        Helplist helplist = this.baseMapper.selectById(oId);
        helplist.setState(state);
        baseMapper.updateById(helplist);
        return Result.SUCCESS("取消成功");
    }
}
